/*global Backbone, $, _, setTimeout, Isotope, document, console, List, Item, ItemView */

//定义menu
var Menu = Backbone.Model.extend({
    defaults: {
        name: "",
        text: "",
        cur: false
    }
});

var menu = new Menu();

var Menus = Backbone.Collection.extend({
    model: Menu
});

var menus = new Menus();

menus.add({name: "index", text: "介绍", cur: true});
menus.add({name: "list", text: "条目"});
menus.add({name: "help", text: "帮助"});

//定义view
var UserView = Backbone.View.extend({
    el: $("#menu"),
    initialize: function () {
        _.bindAll(this, 'render');
        this.collection = menus;
        this.collection.bind('change', this.render); // collection event binder

        this.render();
    },

    render: function () {
        //Mustache.js style template
        _.templateSettings = {
            interpolate: /\{\{(.+?)\}\}/g
        };

        var template = _.template("<a href='#!{{name}}' {{cur}}>{{text}}</a>");

        var html = "";

        _.each(menus.models, function (menu_models) {
            var menu = menu_models.attributes;
            var cur = menu.cur ? " class='menu-sel' " : "";

            html += template({cur: cur, name: menu.name, text: menu.text});
        });

        $(this.el).html(html);
    }
});

var user_view = new UserView();

//定义显示区域
var Content = Backbone.Model.extend({
    defaults: {
        text: "暂无内容"
    }
});

var content = new Content();

var ContentView = Backbone.View.extend({
    el: $("#content"),

    events: {
        'click button#add': 'addBtn',
        'click button#active_item': 'active_item',
        'click button#archive_item': 'archive_item'
    },

    initialize: function () {
        _.bindAll(this, 'beforeRender', 'render', 'afterRender', 'addItem', 'addBtn', 'appendItem');
        var _this = this;
        this.render = _.wrap(this.render, function (render) {
            _this.beforeRender();
            render();
            _this.afterRender();
            return _this;
        });

        this.collection = new List();
        this.collection.bind('add', this.appendItem); // collection event binder
        this.model.bind('change', this.render);
        this.counter = 0;
        this.index();
    },

    render: function () {
        var buttons = "<button id='add' class='btn btn-default btn-sm'>新增条目</button>";
        buttons += "<button id='active_item' class='btn btn-default btn-sm'>活动条目</button>";
        buttons += "<button id='archive_item' class='btn btn-default btn-sm'>归档条目</button>";

        $(this.el).html("<div class='topToolBar'>" + buttons + "</div>");

        var loading = '<div id="floatingCirclesG">' +
            ' <div class="f_circleG" id="frotateG_01"> </div>' +
            ' <div class="f_circleG" id="frotateG_02"> </div>' +
            ' <div class="f_circleG" id="frotateG_03"> </div>' +
            ' <div class="f_circleG" id="frotateG_04"> </div>' +
            ' <div class="f_circleG" id="frotateG_05"> </div>' +
            ' <div class="f_circleG" id="frotateG_06"> </div>' +
            ' <div class="f_circleG" id="frotateG_07"> </div>' +
            ' <div class="f_circleG" id="frotateG_08"> </div>' +
            ' </div>';

        $(this.el).append("<ul id='question-list' style='margin: 0; padding: 0;'>" + loading + "</ul>");
        var self = this;
        _(this.collection.models).each(function (item) { // in case collection is not empty
            self.appendItem(item);
        }, this);


    },

    index: function () {
        var html = '主页';
        $(this.el).html(html);
        return this;
    },

    list: function (item_type) {
        var loading = '<div id="floatingCirclesG">' +
            ' <div class="f_circleG" id="frotateG_01"> </div>' +
            ' <div class="f_circleG" id="frotateG_02"> </div>' +
            ' <div class="f_circleG" id="frotateG_03"> </div>' +
            ' <div class="f_circleG" id="frotateG_04"> </div>' +
            ' <div class="f_circleG" id="frotateG_05"> </div>' +
            ' <div class="f_circleG" id="frotateG_06"> </div>' +
            ' <div class="f_circleG" id="frotateG_07"> </div>' +
            ' <div class="f_circleG" id="frotateG_08"> </div>' +
            ' </div>';

        $('#content').html(loading);

        var me = this;
        me.collection.reset();

        $.ajax({
            url: "http://www.tomtalk.net/getList.php",
            type: "POST",
            data: {item_type: item_type, start: 0, limit: 1},
            timeout: 6000,
            dataType: "json",
            success: function (result) {
                //console.log(result);
                _.each(result, function (row) {
                    me.add(row);
                });
                me.render();
            },
            error: function () {
                $('#content').html('<div class="error">数据读取超时。<br/>Fuck! 找运维来处理：13417446590<br/></div>');
            }
        });

        $.ajax({
            url: "http://dev.tomtalk.net/get_session.php",
            type: "POST",
            data: {item_type: item_type, start: 0, limit: 1},
            timeout: 6000,
            dataType: "json",
            success: function (result) {
                console.log(result);
                //me.render();
            },
            error: function () {
                //$('#content').html('<div class="error">数据读取超时。<br/>Fuck! 找运维来处理：13417446590<br/></div>');
            }
        });
    },

    active_item: function () {
        this.list('active');
    },

    archive_item: function () {
        this.list('archive');
    },

    help: function () {
        var html = 'help';
        $(this.el).html(html);
        return this;
    },

    addItem: function () {
        this.counter += 1;
        var item = new Item();
        item.set({
            question: item.get('question') + this.counter // modify item defaults
        });

        this.collection.unshift(item); // add item to collection; view is updated via event 'add'
    },

    add: function (row) {
        var item = new Item();
        item.set({
            _id: row._id,
            question: row.question,
            answer: row.answer,
            explain: row.explain,
            priority: parseInt(row.priority, 10),
            is_memo: parseInt(row.is_memo, 10),
            type: row.type,
            sync_state: row.sync_state
        });

        this.collection.add(item); // add item to collection; view is updated via event 'add'
    },

    appendItem: function (item) {
        var itemView = new ItemView({
            model: item
        });

        $('ul', this.el).prepend(itemView.render().el);
    },

    addBtn: function (item) {
        this.addItem();
        this.isoArrange();
    },

    beforeRender: function () {
        //none
    },

    afterRender: function () {
        $('#floatingCirclesG').remove();

        if (this.collection.length === 0) {
            $('#content').append('<div class="error">没内容啊！赶紧的自己加些。</div>');
        } else {
            this.isoInit();
        }
    },

    isoInit: function () {
        var $container = $('#question-list');
        $container.isotope({
            itemSelector: '.question-item'
        });
    },

    isoArrange: function () {
        var iso = new Isotope(document.querySelector('#question-list'));
        iso.arrange();
    }
});

var content_view = new ContentView({model: List});

var PageRouter = Backbone.Router.extend({
    routes: {
        "!": "index",
        "!index": "index",
        "!list": "list",
        "!help": "help"
    },

    index: function () {
        this.setMenu('index');
        content_view.index();
    },

    list: function () {
        this.setMenu('list');
        content_view.list('active');
    },

    help: function () {
        this.setMenu('help');
        content_view.help();
    },

    setMenu: function (item) {
        _.each(menus.models, function (menu) {
            menu.set({cur: (menu.get("name") === item ? true : false)});
        });
    }
});

var page_router = new PageRouter();

Backbone.history.start();

//end file
